package br.ufpe.cin.mac.middleware.connectors.concrete;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import javax.management.NotificationBroadcasterSupport;

import br.ufpe.cin.mac.util.Constants;


public class UDP extends NotificationBroadcasterSupport implements UDPMBean {

	private DatagramSocket connection;
	private String host;
	
	private int clientport;
	private boolean server;
	
	public UDP(){
	
		this.server = true;
	}
	
	public UDP(String host){
		this();
		this.host = host;
		this.server = false;
	}
	
	public void connect() throws SocketException {
		if(server){  // Server Type
			System.err.println("Server Connection");
			this.connection = new DatagramSocket(Constants.UDP_PORT);
		}
		else {  // Client Type
			System.err.println("Client Connection");
			this.connection = new DatagramSocket();
		}
	}

	public void disconnect() {
		this.connection.disconnect();
		this.connection.close();
	}

	public void send(byte[] data) throws IOException {
		DatagramPacket pacote = null; 
		InetAddress addr = InetAddress.getByName(this.host);
		if(server){
			pacote = new DatagramPacket(data, data.length, addr,this.clientport);
		}
		else{
			pacote = new DatagramPacket(data, data.length, addr,Constants.UDP_PORT);
		}
			
		this.connection.send(pacote);
	}
	
	public byte[] receive() throws IOException {
		byte[] data = new byte[1024];
		DatagramPacket pack = new DatagramPacket(data,data.length);
		this.connection.receive(pack);
		this.host = pack.getAddress().getHostAddress();
		this.clientport = pack.getPort();
		
		data = pack.getData();
		//System.err.println(new String(data).trim());
		return data;
	}

}
